/*
https://leetcode-cn.com/problems/bag-of-tokens/solution/ling-pai-fang-zhi-by-leetcode/
 */
import java.util.Arrays;

public class Solution948 {
    public int bagOfTokensScore(int[] tokens, int power) {
        int ans=0;
        Arrays.sort(tokens);
        int l=0,r=tokens.length-1;
        int cur=0;
        while (l<=r){
            if (power>=tokens[l]){
                cur++;
                ans=Math.max(ans,cur);
                power-=tokens[l];
                l++;
            }else if (cur>0){
                cur--;
                power+=tokens[r];
                r--;
            }else {
                break;
            }
        }
        return ans;
    }

    public static void main(String[] args) {
        System.out.println(new Solution948().bagOfTokensScore(new int[]{26,78,43,36,6,87,70,91,45,68}, 12));
    }
}
